import { ref, toRaw } from 'vue'
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import { constantRoutes } from '@/router'
import Layout from '@/layout/index.vue'
import ParentView from '@/components/ParentView/index.vue'
import { getUserAsyncRoutes as getAsyncRoutes, type MenuItem } from '@/apis'
import { mapTree } from 'xe-utils'
import { transformPathToName } from '@/utils'
import menuData from '@/mock/_data/system_menu'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('@/views/**/*.vue')

/** 加载模块 */
export const loadView = (view: string) => {
  let res
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0]
    if (dir === view) {
      res = () => modules[path]()
    }
  }
  return res
}

/** 将component由字符串转成真正的模块 */
const transformComponentView = (component: string) => {
  if (component === 'Layout') {
    return Layout as never
  } else if (component === 'ParentView') {
    return ParentView as never
  } else {
    return loadView(component) as never
  }
}

/**
 * @description 前端来做排序、格式化
 * @params {menus} 后端返回的路由数据，已经根据当前用户角色过滤掉了没权限的路由
 * 1. 对后端返回的路由数据进行排序，格式化
 * 2. 同时将component由字符串转成真正的模块
 */
const formatAsyncRoutes = (menus: MenuItem[]) => {
  if (!menus.length) return []
  menus.sort((a, b) => (b?.sort ?? 0) - (a?.sort ?? 0)) // 排序
  let redirect = null;
  const regex = /page\/(.*?)\.html/;
  let pathName = ''
  let path = ''

  const routes = mapTree(menus, (item) => {
    if (item.child && item.child.length) {
      item.child.sort((a, b) => (b?.sort ?? 0) - (a?.sort ?? 0)) // 排序
      // const match = item.child[0].href.match(regex);
      // if (match) {
      //   redirect = match[1] + '/index'; // 提取匹配到的第一个捕获组
      // }
    }
    // const match = item.href.match(regex);
    // if (match) {
    //   pathName = match[1]; // 提取匹配到的第一个捕获组
    //   path = pathName + '/index'
    // }
    // 由于这里适配老后台。返回的是page/xxx.html
    return {
      // path: '/' + path,
      // name: transformPathToName(pathName),
      // component: transformComponentView(path),
      // redirect: redirect,
      path: item.path,
      name: transformPathToName(item.path),
      component: transformComponentView(item.component),
      redirect: item.redirect,
      meta: {
        hidden: false,
        keepAlive: false,
        title: item.title,
        svgIcon: item.svgIcon,
        icon: item.icon,
        affix: false,
        breadcrumb: true,
        // showInTabs: true,
        // activeMenu: '',
        // alwaysShow: false
      },
    }
  })//将children映射child

  // }, { children: 'child' })//将children映射child
  return routes as RouteRecordRaw[]
}

const storeSetup = () => {
  // 所有路由(常驻路由 + 动态路由)
  const routes = ref<RouteRecordRaw[]>([])
  // 动态路由(异步路由)
  const asyncRoutes = ref<RouteRecordRaw[]>([])

  // 合并路由
  const setRoutes = (data: RouteRecordRaw[]) => {
    routes.value = constantRoutes.concat(data)
    asyncRoutes.value = data
    console.log('路由', toRaw(routes.value))
  }

  // 生成路由
  const generateRoutes = (): Promise<RouteRecordRaw[]> => {
    return new Promise((resolve) => {
      // 向后端请求路由数据 这个接口已经根据用户角色过滤了没权限的路由(后端根据用户角色过滤路由显得比较安全些)
      getAsyncRoutes().then((res) => {
        let resData = JSON.parse(res)
        console.log(resData);
        let test = [
          {
            path: '/',
            component: 'Layout',
            redirect: '/customer-list/index',
            "title": "用户管理",
            icon: 'icon-user',
            children: [
              {
                path: '/customer-list/index',
                component: 'customer-list/index',
                redirect: '',
                title: '用户管理',
                icon: 'icon-user',
              }
            ],
          },
          {
            path: '/demand-list',
            component: 'Layout',
            redirect: '/demand-list/index',
            title: "需求中心",
            icon: 'icon-bookmark',
            children: [
              {
                path: '/demand-list/index',
                component: 'demand-list/index',
                redirect: '',
                type: 2,
                title: '需求中心',
                icon: 'icon-bookmark',
              }
            ],
          },
          {
            path: '/transaction-records',
            component: 'Layout',
            redirect: '/transaction-records/index',
            title: "交易流水",
            icon: 'icon-select-all',
            children: [
              {
                path: '/transaction-records/index',
                component: 'transaction-records/index',
                redirect: '',
                type: 2,
                title: '交易流水',
                icon: 'icon-select-all',
              }
            ],
          },
          {
            "id": 22,
            path: '/task-center',
            component: 'Layout',
            redirect: '/task-center/index',
            "title": "任务中心",
            icon: 'icon-check-square',
            children: [
              {
                path: '/task-center/index',
                component: 'task-center/index',
                redirect: '',
                icon: 'icon-list',
                title: '任务管理',
              },
              {
                path: '/task-center/my-task',
                component: 'task-center/my-task',
                redirect: '',
                icon: 'icon-list',
                title: '我的任务',
              }
            ],
          },
          {
            path: '/kefu-chat',
            component: 'Layout',
            redirect: '/kefu-chat/index',
            "title": "客服功能",
            icon: 'icon-message',
            children: [
              {
                path: '/kefu-chat/index',
                component: 'kefu-chat/index',
                redirect: '',
                title: 'AISEO在线聊天',
                icon: 'icon-message',
              }
            ],
          },
          {
            path: '/appointment-list',
            component: 'Layout',
            redirect: '/appointment-list/index',
            "title": "预约单管理",
            icon: 'icon-schedule',
            children: [
              {
                path: '/appointment-list/index',
                component: 'appointment-list/index',
                redirect: '',
                title: '预约单列表',
                icon: 'icon-schedule',
              }
            ],
          },
          {
            path: '/admin-list',
            component: 'Layout',
            redirect: '/admin-list/index',
            "title": "群组管理",
            icon: 'icon-user-group',
            children: [
              {
                path: '/admin-list/index',
                component: 'admin-list/index',
                redirect: '',
                title: '管理员列表',
                icon: 'icon-list',
              },
              {
                path: '/admin-list/admin-role',
                component: 'admin-list/admin-role',
                redirect: '',
                title: '部门列表',
                icon: 'icon-list',
              },
              {
                path: '/admin-list/admin-log',
                component: 'admin-list/admin-log',
                redirect: '',
                title: '操作日志',
                icon: 'icon-list',
              },
            ],
          },
        ]

        const asyncRoutes = formatAsyncRoutes(resData)
        // const asyncRoutes = formatAsyncRoutes(menuData)
        setRoutes(asyncRoutes)
        resolve(asyncRoutes)
      })
    })
  }

  return {
    routes,
    asyncRoutes,
    generateRoutes
  }
}

export const useRouteStore = defineStore('route', storeSetup, { persist: true })
